<template>
  <div class="app-container">
    <!-- 活动详情展示 -->
    <el-card class="activity-card" shadow="never" v-if="activityDetail">
      <div class="activity-header">
        <div class="activity-image">
          <el-image
            :src="activityDetail.imageUrl"
            fit="cover"
            style="width: 100%; height: 300px; border-radius: 12px;"
            v-if="activityDetail.imageUrl"
          />
          <div class="no-image" v-else>
            <el-icon size="60"><Picture /></el-icon>
            <p>暂无活动图片</p>
          </div>
        </div>
        
        <div class="activity-info">
          <div class="activity-title">
            <h1>{{ activityDetail.title }}</h1>
            <el-tag :type="getStatusType(activityDetail.status)" size="large">
              {{ getStatusText(activityDetail.status) }}
            </el-tag>
          </div>
          
          <div class="activity-description">
            <p>{{ activityDetail.description }}</p>
          </div>
          
          <div class="activity-time">
            <div class="time-item">
              <el-icon><Calendar /></el-icon>
              <span>开始时间：{{ parseTime(activityDetail.startTime) }}</span>
            </div>
            <div class="time-item">
              <el-icon><Clock /></el-icon>
              <span>结束时间：{{ parseTime(activityDetail.endTime) }}</span>
            </div>
          </div>
          
          <!-- 倒计时 -->
          <div class="countdown" v-if="showCountdown">
            <div class="countdown-title">距离活动开始还有：</div>
            <div class="countdown-timer">
              <div class="countdown-item">
                <span class="countdown-number">{{ countdown.days }}</span>
                <span class="countdown-label">天</span>
              </div>
              <div class="countdown-item">
                <span class="countdown-number">{{ countdown.hours }}</span>
                <span class="countdown-label">时</span>
              </div>
              <div class="countdown-item">
                <span class="countdown-number">{{ countdown.minutes }}</span>
                <span class="countdown-label">分</span>
              </div>
              <div class="countdown-item">
                <span class="countdown-number">{{ countdown.seconds }}</span>
                <span class="countdown-label">秒</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 商品列表 -->
    <el-card class="products-card" shadow="never" v-if="products.length > 0">
      <template #header>
        <div class="card-header">
          <span>活动商品</span>
          <el-button type="primary" @click="refreshProducts">刷新</el-button>
        </div>
      </template>
      
      <el-row :gutter="20">
        <el-col :span="8" v-for="product in products" :key="product.id">
          <el-card class="product-item" shadow="hover">
            <div class="product-image">
              <el-image
                :src="product.imageUrl"
                fit="cover"
                style="width: 100%; height: 200px; border-radius: 8px;"
                v-if="product.imageUrl"
              />
              <div class="no-product-image" v-else>
                <el-icon size="40"><Picture /></el-icon>
              </div>
            </div>
            
            <div class="product-info">
              <h3 class="product-name">{{ product.productName }}</h3>
              <p class="product-description">{{ product.description }}</p>
              
              <div class="product-price">
                <div class="price-item">
                  <span class="price-label">原价：</span>
                  <span class="original-price">¥{{ product.originalPrice }}</span>
                </div>
                <div class="price-item">
                  <span class="price-label">活动价：</span>
                  <span class="activity-price">¥{{ product.activityPrice }}</span>
                </div>
              </div>
              
              <div class="product-stock">
                <el-progress 
                  :percentage="getStockPercentage(product)" 
                  :color="getStockColor(product)"
                  :stroke-width="8"
                />
                <div class="stock-info">
                  <span>库存：{{ product.currentStock }}/{{ product.totalStock }}</span>
                  <span>限购：{{ product.limitPerUser }}件</span>
                </div>
              </div>
              
              <div class="product-actions">
                <el-input-number
                  v-model="product.quantity"
                  :min="1"
                  :max="Math.min(product.currentStock, product.limitPerUser)"
                  size="small"
                  style="width: 120px;"
                />
                <el-button
                  type="primary"
                  :disabled="!canGrab(product)"
                  @click="handleGrab(product)"
                  :loading="product.grabbing"
                >
                  {{ getGrabButtonText(product) }}
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 抢购结果对话框 -->
    <el-dialog title="抢购结果" v-model="grabResultOpen" width="500px" append-to-body>
      <div class="grab-result" v-if="grabResult">
        <div class="result-icon">
          <el-icon :class="grabResult.success ? 'success-icon' : 'error-icon'" size="60">
            <CircleCheckFilled v-if="grabResult.success" />
            <CircleCloseFilled v-else />
          </el-icon>
        </div>
        
        <div class="result-content">
          <h3>{{ grabResult.message }}</h3>
          
          <div class="order-info" v-if="grabResult.success">
            <div class="order-item">
              <label>订单号：</label>
              <span>{{ grabResult.orderNo }}</span>
            </div>
            <div class="order-item">
              <label>订单金额：</label>
              <span class="order-amount">¥{{ grabResult.orderAmount }}</span>
            </div>
            <div class="order-item">
              <label>支付截止时间：</label>
              <span>{{ parseTime(grabResult.expireTime) }}</span>
            </div>
            <div class="order-item">
              <label>剩余支付时间：</label>
              <span class="countdown-text">{{ formatCountdown(grabResult.countdownSeconds) }}</span>
            </div>
          </div>
        </div>
        
        <div class="result-actions">
          <el-button type="primary" @click="handlePay" v-if="grabResult.success">
            立即支付
          </el-button>
          <el-button @click="handleCancel" v-if="grabResult.success">
            取消订单
          </el-button>
          <el-button @click="grabResultOpen = false">
            关闭
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 支付对话框 -->
    <el-dialog title="订单支付" v-model="payOpen" width="400px" append-to-body>
      <div class="pay-content">
        <div class="pay-info">
          <div class="pay-item">
            <label>订单号：</label>
            <span>{{ currentOrder?.orderNo }}</span>
          </div>
          <div class="pay-item">
            <label>支付金额：</label>
            <span class="pay-amount">¥{{ currentOrder?.orderAmount }}</span>
          </div>
        </div>
        
        <div class="pay-methods">
          <h4>选择支付方式：</h4>
          <el-radio-group v-model="payMethod">
            <el-radio label="alipay">支付宝</el-radio>
            <el-radio label="wechat">微信支付</el-radio>
            <el-radio label="bank">银行卡</el-radio>
          </el-radio-group>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmPay" :loading="paying">
            确认支付
          </el-button>
          <el-button @click="payOpen = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ActivityGrab">
import { 
  readActivity, 
  getActivityDetail 
} from "@/api/activity/activity.js"

const { proxy } = getCurrentInstance()

const route = useRoute()
const activityId = ref(route.params.id || route.query.id)

const activityDetail = ref(null)
const products = ref([])
const loading = ref(true)
const showCountdown = ref(false)
const countdown = ref({ days: 0, hours: 0, minutes: 0, seconds: 0 })
const countdownTimer = ref(null)

// 抢购相关
const grabResultOpen = ref(false)
const grabResult = ref(null)
const payOpen = ref(false)
const currentOrder = ref(null)
const payMethod = ref('alipay')
const paying = ref(false)

/** 获取活动详情 */
function getActivityDetail() {
  loading.value = true
  getActivityDetail(activityId.value).then(response => {
    activityDetail.value = response.data
    products.value = response.data.products || []
    
    // 初始化商品数量
    products.value.forEach(product => {
      product.quantity = 1
      product.grabbing = false
    })
    
    // 检查活动时间
    checkActivityTime()
    
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

/** 检查活动时间并启动倒计时 */
function checkActivityTime() {
  if (!activityDetail.value) return
  
  const now = new Date().getTime()
  const startTime = new Date(activityDetail.value.startTime).getTime()
  const endTime = new Date(activityDetail.value.endTime).getTime()
  
  if (now < startTime) {
    // 活动未开始，显示倒计时
    showCountdown.value = true
    startCountdown(startTime)
  } else if (now >= startTime && now <= endTime) {
    // 活动进行中
    showCountdown.value = false
  } else {
    // 活动已结束
    showCountdown.value = false
  }
}

/** 启动倒计时 */
function startCountdown(targetTime) {
  const updateCountdown = () => {
    const now = new Date().getTime()
    const distance = targetTime - now
    
    if (distance > 0) {
      const days = Math.floor(distance / (1000 * 60 * 60 * 24))
      const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
      const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))
      const seconds = Math.floor((distance % (1000 * 60)) / 1000)
      
      countdown.value = { days, hours, minutes, seconds }
    } else {
      // 倒计时结束，刷新页面
      clearInterval(countdownTimer.value)
      showCountdown.value = false
      getActivityDetail()
    }
  }
  
  updateCountdown()
  countdownTimer.value = setInterval(updateCountdown, 1000)
}

/** 刷新商品列表 */
function refreshProducts() {
  getActivityDetail()
}

/** 获取状态类型 */
function getStatusType(status) {
  const statusMap = {
    '0': 'info',
    '1': 'warning',
    '2': 'success',
    '3': 'danger',
    '4': 'info'
  }
  return statusMap[status] || 'info'
}

/** 获取状态文本 */
function getStatusText(status) {
  const statusMap = {
    '0': '草稿',
    '1': '待发布',
    '2': '已发布',
    '3': '已结束',
    '4': '已暂停'
  }
  return statusMap[status] || '未知'
}

/** 获取库存百分比 */
function getStockPercentage(product) {
  if (product.totalStock === 0) return 0
  return Math.round((product.currentStock / product.totalStock) * 100)
}

/** 获取库存颜色 */
function getStockColor(product) {
  const percentage = getStockPercentage(product)
  if (percentage > 50) return '#67C23A'
  if (percentage > 20) return '#E6A23C'
  return '#F56C6C'
}

/** 检查是否可以抢购 */
function canGrab(product) {
  if (!activityDetail.value) return false
  
  const now = new Date().getTime()
  const startTime = new Date(activityDetail.value.startTime).getTime()
  const endTime = new Date(activityDetail.value.endTime).getTime()
  
  return now >= startTime && now <= endTime && 
         activityDetail.value.status === '2' && 
         product.currentStock > 0
}

/** 获取抢购按钮文本 */
function getGrabButtonText(product) {
  if (!canGrab(product)) {
    if (product.currentStock <= 0) return '已售罄'
    if (activityDetail.value?.status !== '2') return '活动未开始'
    return '抢购'
  }
  return '抢购'
}

/** 处理抢购 */
function handleGrab(product) {
  if (!canGrab(product)) return
  
  product.grabbing = true
  
  // 模拟抢购请求
  setTimeout(() => {
    const success = Math.random() > 0.3 // 70%成功率
    
    if (success) {
      grabResult.value = {
        success: true,
        message: '抢购成功，请尽快付款！',
        orderNo: 'ORDER' + Date.now(),
        orderAmount: (product.activityPrice * product.quantity).toFixed(2),
        expireTime: new Date(Date.now() + 5 * 60 * 1000).toISOString(), // 5分钟后过期
        countdownSeconds: 300
      }
      currentOrder.value = grabResult.value
    } else {
      grabResult.value = {
        success: false,
        message: '抢购失败，请稍后重试！'
      }
    }
    
    product.grabbing = false
    grabResultOpen.value = true
    
    // 刷新商品库存
    if (success) {
      product.currentStock -= product.quantity
    }
  }, 1000)
}

/** 处理支付 */
function handlePay() {
  payOpen.value = true
  grabResultOpen.value = false
}

/** 确认支付 */
function confirmPay() {
  paying.value = true
  
  // 模拟支付请求
  setTimeout(() => {
    paying.value = false
    payOpen.value = false
    proxy.$modal.msgSuccess('支付成功！')
    
    // 刷新活动详情
    getActivityDetail()
  }, 2000)
}

/** 取消订单 */
function handleCancel() {
  proxy.$modal.confirm('确定要取消订单吗？').then(() => {
    grabResultOpen.value = false
    proxy.$modal.msgSuccess('订单已取消')
    
    // 恢复库存
    const product = products.value.find(p => p.id === currentOrder.value?.productId)
    if (product) {
      product.currentStock += currentOrder.value?.quantity || 1
    }
  })
}

/** 格式化倒计时 */
function formatCountdown(seconds) {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
}

/** 时间格式化 */
function parseTime(time) {
  if (!time) return ''
  return new Date(time).toLocaleString('zh-CN')
}

// 组件卸载时清理定时器
onUnmounted(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }
})

// 页面加载时获取活动详情
onMounted(() => {
  if (activityId.value) {
    getActivityDetail()
  }
})
</script>

<style scoped>
.activity-card {
  margin-bottom: 20px;
}

.activity-header {
  display: flex;
  gap: 24px;
}

.activity-image {
  flex: 0 0 400px;
}

.no-image {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300px;
  background: #f5f7fa;
  border-radius: 12px;
  color: #909399;
}

.activity-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.activity-title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.activity-title h1 {
  margin: 0;
  color: #303133;
  font-size: 28px;
}

.activity-description p {
  margin: 0;
  color: #606266;
  line-height: 1.6;
  font-size: 16px;
}

.activity-time {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.time-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
}

.countdown {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  border-radius: 12px;
  color: white;
}

.countdown-title {
  font-size: 16px;
  margin-bottom: 16px;
  text-align: center;
}

.countdown-timer {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.countdown-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.countdown-number {
  font-size: 32px;
  font-weight: bold;
  background: rgba(255, 255, 255, 0.2);
  padding: 8px 12px;
  border-radius: 8px;
  min-width: 60px;
  text-align: center;
}

.countdown-label {
  font-size: 14px;
  opacity: 0.8;
}

.products-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-item {
  margin-bottom: 20px;
  transition: transform 0.3s ease;
}

.product-item:hover {
  transform: translateY(-4px);
}

.product-image {
  margin-bottom: 16px;
}

.no-product-image {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  background: #f5f7fa;
  border-radius: 8px;
  color: #909399;
}

.product-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.product-name {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 500;
}

.product-description {
  margin: 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.4;
}

.product-price {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.price-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.price-label {
  color: #909399;
  font-size: 14px;
}

.original-price {
  color: #909399;
  text-decoration: line-through;
  font-size: 14px;
}

.activity-price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}

.product-stock {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.stock-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.product-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.grab-result {
  text-align: center;
  padding: 20px;
}

.result-icon {
  margin-bottom: 20px;
}

.success-icon {
  color: #67c23a;
}

.error-icon {
  color: #f56c6c;
}

.result-content h3 {
  margin: 0 0 20px 0;
  color: #303133;
}

.order-info {
  text-align: left;
  background: #f5f7fa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.order-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.order-item:last-child {
  margin-bottom: 0;
}

.order-item label {
  color: #606266;
  font-weight: 500;
}

.order-amount {
  color: #f56c6c;
  font-weight: bold;
}

.countdown-text {
  color: #e6a23c;
  font-weight: bold;
}

.result-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.pay-content {
  padding: 20px 0;
}

.pay-info {
  margin-bottom: 24px;
}

.pay-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.pay-item label {
  color: #606266;
  font-weight: 500;
}

.pay-amount {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}

.pay-methods h4 {
  margin: 0 0 16px 0;
  color: #303133;
}

.dialog-footer {
  text-align: right;
}
</style> 